package skills.jssvc.deu.cn.skillsecond.programming1;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;

import skills.jssvc.deu.cn.skillsecond.MyApplication;
import skills.jssvc.deu.cn.skillsecond.R;
import skills.jssvc.deu.cn.skillsecond.bean.Balance;
import skills.jssvc.deu.cn.skillsecond.util.HttpRequest;
import skills.jssvc.deu.cn.skillsecond.util.SqlHelper;

/**
 * Created by Administrator on 2019/3/12 0012.
 */

public class MyAccount2 extends Fragment {
    private final String TAG = "MyAccount2";
    private View view;
    private TextView balanceTv;
    private Spinner carSpinner;
    private ArrayAdapter<String> spinnerAdapter;
    private EditText amountEd;
    private Button queryBtn,okBtn;

    private SqlHelper helper;
    private SQLiteDatabase db;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.frag_myaccount2, container, false);
        initView();
        setListeners();
        return view;
    }

    private void initView(){
        balanceTv = (TextView)view.findViewById(R.id.frag1_myaccount2_balance);
        carSpinner = (Spinner)view.findViewById(R.id.frag1_myaccount2_car_spinner);
        amountEd = (EditText) view.findViewById(R.id.frag1_myaccount2_amount_et);
        queryBtn = (Button)view.findViewById(R.id.frag1_myaccount2_query_btn);
        okBtn = (Button)view.findViewById(R.id.frag1_myaccount2_top_btn);
//        String[] cars = new String[]{"1","2","3","4"};
//        spinnerAdapter = new ArrayAdapter<String>(MyApplication.appContext,android.R.layout.simple_spinner_item,cars);
//        spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//        carSpinner.setAdapter(spinnerAdapter);
    }

    private void setListeners(){
        queryBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                httpQuery(carSpinner.getSelectedItemPosition()+1);
            }
        });
        okBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String money = amountEd.getText().toString().trim();
                if(!money.equals("")){
                    int car = carSpinner.getSelectedItemPosition()+1;
                    carUp(car,Integer.valueOf(money));
                    queryRecord();
                }
            }
        });

    }

    private void httpQuery(int car){
        String param = "{\"CarId\":"+String.valueOf(car)+", \"UserName\":\"user1\"}";
        HttpRequest.post("GetCarAccountBalance", param, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                Balance balance = new Gson().fromJson(jsonObject.toString(), Balance.class);
                balanceTv.setText(String.valueOf(balance.getBalance()));
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Toast.makeText(MyApplication.appContext,"数据请求出错了",Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void carUp(final int car, final int money){
        String param = "{\"CarId\":"+String.valueOf(car)+",\"Money\":"+String.valueOf(money)+", \"UserName\":\"user1\"}";
        HttpRequest.post("SetCarAccountRecharge", param, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                try {
                    if(jsonObject.getString("RESULT").equals("S")){
                        httpQuery(car);
                        upRecord(car,money);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Toast.makeText(MyApplication.appContext,"数据请求出错了",Toast.LENGTH_SHORT).show();

            }
        });
    }

    private void upRecord(int car,int amount){
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:MM:ss");
        String time = format.format(System.currentTimeMillis());
        helper = new SqlHelper(MyApplication.appContext,SqlHelper.DA_NAME,null,1);
        db = helper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("carId",car);
        values.put("amount",amount);
        values.put("time",time);
        values.put("user","user1");
        db.insert(SqlHelper.table_top,null,values);
        values.clear();
        db.close();
    }

    private void queryRecord(){
        helper = new SqlHelper(MyApplication.appContext, SqlHelper.DA_NAME, null, 1);
        db = helper.getWritableDatabase();
        Cursor cursor = db.query(SqlHelper.table_top,null,null,null,null,null,null);
        if(cursor.moveToLast()){
            Log.d(TAG, "queryRecord: cursor = " + cursor.getString(cursor.getColumnIndex("time")));
        }
    }


}
